package cn.edu.lcvc.ebuy_ruanjian2.web.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 用于验证账户的登录状态
 * **/

public class LoginForAdminInterceptor extends HandlerInterceptorAdapter {

    /**
     *  在执行要拦截的spring mvc控制器前执行。
     *如果返回true，表示不拦截；如果返回false，表示拦截，链接之后无法访问spring mvc控制器
     * @param request
     * @param response
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result=false;//默认拦截
        //验证账户登录是否已经登录
        HttpSession session=request.getSession();
        if(session.getAttribute("admin")!=null){//如果已经登录
            result=true;
        }else{//如果没有登录
            //返回到账户的登录页面
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                    + path + "/";
            response.sendRedirect(basePath+ "jsp/backstage/login.jsp");
        }
        return result;
    }
}
